package cn.exrick.front.controller;

import cn.exrick.common.constant.CommonConstant;
import cn.exrick.common.pojo.DataTablesResult;
import cn.exrick.common.pojo.Result;
import cn.exrick.common.pojo.ZTreeNode;
import cn.exrick.common.utils.IDUtil;
import cn.exrick.common.utils.ResultUtil;
import cn.exrick.manager.dto.front.MemberLoginRegist;
import cn.exrick.manager.pojo.TbMember;
import cn.exrick.manager.pojo.TbNav;
import cn.exrick.manager.pojo.TbNews;
import cn.exrick.manager.pojo.TbSysSetting;
import cn.exrick.manager.service.*;
import cn.exrick.sso.service.LoginService;
import cn.exrick.sso.service.MemberService;
import cn.exrick.sso.service.RegisterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
@Api(description = "会员注册登录")
public class MemberController {

    private final static Logger log= LoggerFactory.getLogger(MemberController.class);

    @Autowired
    private LoginService loginService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private EmailTemplateService emailTemplateService;
    @Autowired
    private ItemCatService itemCatService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private SysSettingService sysSettingService;

    @Value("${FILE_STORE_PATH}")
    private String storePath;
    @Value("${IMAGE_ACCESS_URL}")
    private String imageUrl;

    @ResponseBody
    @RequestMapping(value = "/member/login",method = RequestMethod.POST)
    @ApiOperation(value = "用户登录")
    public Result<TbMember> login(MemberLoginRegist memberLoginRegist,
                                HttpSession session){

        Result<TbMember> result = loginService.userLogin(memberLoginRegist.getUserName(), memberLoginRegist.getUserPwd());
        TbMember member = result.getResult();
        session.setAttribute(CommonConstant.USER_SESSION, member);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/member/logout",method = RequestMethod.POST)
    @ApiOperation(value = "退出登录")
    public Result<Object> logout(HttpSession session){
        session.invalidate();
        return new ResultUtil<Object>().setData(null);
    }

    @ResponseBody
    @RequestMapping(value = "/member/register",method = RequestMethod.POST)
    @ApiOperation(value = "用户注册")
    public Result<Object> register(MemberLoginRegist memberLoginRegist,
                                   HttpSession session){
        String code =  (String) session.getAttribute("code");
        String email = (String) session.getAttribute("email");
        if(code != null && !code.equals(memberLoginRegist.getVerificationCode())){
            return new ResultUtil<>().setErrorMsg("验证码不正确");
        }

        if(email != null && !email.equals(memberLoginRegist.getEmail())){
            return new ResultUtil<>().setErrorMsg("请使用接收验证码的邮箱注册");
        }

        return registerService.register(memberLoginRegist);
    }

    @ResponseBody
    @RequestMapping(value = "/member/imgaeUpload",method = RequestMethod.POST)
    @ApiOperation(value = "用户头像上传")
    public Result<Object> imgaeUpload(MultipartFile file){
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + ext;
        try {
            File storeFile=new File(storePath + File.separator + fileName);
            if(!storeFile.getParentFile().exists()){
                storeFile.getParentFile().mkdirs();
            }

            file.transferTo(storeFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        memberService.imageUpload(userId,token,fileName);
        return new ResultUtil<Object>().setData(fileName);
    }

    /**
     * 发送验证码
     * @param email
     * @return
     */
    @ResponseBody
    @RequestMapping(value ="/member/sendVerificationCode",method = RequestMethod.POST)
    public Result<Object> sendVerificationCode(HttpSession session,String email,String findPassword){
        boolean notExist = registerService.checkData(email, 3, null);
        if(notExist && "true".equals(findPassword)){
            return new ResultUtil<Object>().setErrorMsg("该邮箱未注册！");
        }

        if(!notExist && "false".equals(findPassword)){
            return new ResultUtil<Object>().setErrorMsg("该邮箱已被注册！");
        }

        String code = IDUtil.getOrderCode();
        String content = "尊敬的用户，您好，您的验证码是："+code;
        String subject = "纪念品商城验证码";
        try {
            emailTemplateService.sendEmail(subject,email,content);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultUtil<>().setErrorMsg("验证码发送失败");
        }

        session.setAttribute("code",code);
        session.setAttribute("email", email);
        return new ResultUtil<Object>().setData(null);
    }


    @ResponseBody
    @RequestMapping(value ="/member/checkUserNameRegister",method = RequestMethod.POST)
    public Result<Object> checkUserNameRegister(String userName){
        boolean notExist = registerService.checkData(userName, 1, null);
        if(notExist){
            return new ResultUtil<Object>().setData("");
        }

        return new ResultUtil<Object>().setErrorMsg("该用户名已被注册");
    }


    /**
     * 忘记密码
     * @param memberLoginRegist
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/member/changePassword",method = RequestMethod.POST)
    public Result<Object> changePassword(MemberLoginRegist memberLoginRegist,
                                   HttpSession session){
        String code =  (String) session.getAttribute("code");
        String email = (String) session.getAttribute("email");
        if(code != null && !code.equals(memberLoginRegist.getVerificationCode())){
            return new ResultUtil<>().setErrorMsg("验证码不正确");
        }

        if(email != null && !email.equals(memberLoginRegist.getEmail())){
            return new ResultUtil<>().setErrorMsg("请使用接收验证码的邮箱");
        }


        return memberService.changePassword(memberLoginRegist.getEmail(),memberLoginRegist.getUserPwd());
    }

    @ResponseBody
    @RequestMapping(value = "/member/getPersonalInfo",method = RequestMethod.POST)
    public Result<TbMember> getPersonalInfo(HttpSession session){
        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        TbMember tbMember = memberService.getMemberById(member.getId());
        if(StringUtils.isNotBlank(tbMember.getImage())){
            tbMember.setImage(imageUrl + tbMember.getImage());
        }
        return new ResultUtil<TbMember>().setData(tbMember);
    }


    /**
     * 个人中心修改密码
     * @param oldPassword
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/member/modifyPassword",method = RequestMethod.POST)
    public Result<Object> modifyPassword(String oldPassword,String password,
                                         HttpSession session){
        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        return memberService.modifyPassword(oldPassword,password,member.getId());
    }


    @ResponseBody
    @RequestMapping(value = "/member/update",method = RequestMethod.POST)
    public Result<Object> update(TbMember tbMember,
                                         HttpSession session){
        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        tbMember.setId(member.getId());
        return memberService.updateMemeber(tbMember);
    }

    @RequestMapping(value = "/personalCenter",method = RequestMethod.GET)
    public String myAccount(Model model, HttpSession session){
        setAttribute(model,session);
        return "personal-center";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLogin(Model model, HttpSession session){
        setAttribute(model,session);
        return "login";
    }

    @RequestMapping(value = "/register",method = RequestMethod.GET)
    public String toRegister(Model model, HttpSession session){
        setAttribute(model,session);
        return "register";
    }

    @RequestMapping(value = "/changePassword",method = RequestMethod.GET)
    public String toChangePassword(Model model, HttpSession session){
        setAttribute(model,session);
        return "change-password";
    }

    private void setAttribute(Model model, HttpSession session){
        //商品分类
        List<ZTreeNode> categoryList = itemCatService.getItemCatTree(null);
        model.addAttribute("categoryList",categoryList);
        //导航栏
        List<TbNav> navList=contentService.getNavList();
        model.addAttribute("navList",navList);
        //系统设置
        TbSysSetting setting = sysSettingService.getSetting();
        model.addAttribute("sysSetting",setting);
        //资讯
        DataTablesResult result = newsService.getNewsList(0, 0, 5, new TbNews(), "update_time", "desc");
        model.addAttribute("newsList",result.getData());

        TbMember member = (TbMember) session.getAttribute(CommonConstant.USER_SESSION);
        if(member != null){
            model.addAttribute("member",member);
        }
    }

}
